import json
from typing import Any, Dict
from fastapi import APIRouter, Depends, HTTPException
from minio import Minio
from core.dependencies import get_scheduler, get_sender_tools, get_sio, get_minio_client
from core.logger import log
from services.webhook_service import  process_message, config_webhook
from services.redis_service import AsyncRedisService
from scheduler.msg_async_sch import MsgAsyncScheduler
from utils.result import Result
from fastapi import Request
router = APIRouter()

server = AsyncRedisService()

@router.post("/webhook")
async def webhook(request: Request,scheduler: MsgAsyncScheduler = Depends(get_scheduler),
                  sender_tools = Depends(get_sender_tools),sio=Depends(get_sio),
                  minio_client: Minio = Depends(get_minio_client)):
    """
    开启这个过滤认证--判断webhook这个功能是不是开启状态
    enabled？true
    在配置webhook的数据库中查看
    """
    body =await request.body()
    try:
        raw_data: Dict[str, Any] = json.loads(body.decode('utf-8', errors='ignore'))
    except Exception as e:
        log.error("在webhook_router中的post/webhook方法，非法的请求体参数，不能转化为dict",e)
        return HTTPException(status_code=400, detail="Invalid JSON")
    await process_message(raw_data,sio, server, scheduler, sender_tools, minio_client)
    return {"status": "ok"},200



@router.head("/webhook")
async def health_check():
    return '', 200

@router.post("/webhook/config")
async def webhook_config(data:dict):
    """
    设置webhook的配置
    """
    key = data["auth_key"]
    res_json = await config_webhook(key)
    if res_json["Code"] == 200:
        return Result.success(msg="成功").model_dump()
    else:
        return Result.fail(code=400, msg="设置失败").model_dump()